package indi.kider.server.applet.service;


import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import indi.kider.common.util.HttpClientUtils;
import indi.kider.server.applet.model.User;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class CommServiceImpl implements CommService {

    private final static String APPID = "wxd6f9da591eb0dbd4";
    private final static String SECRET = "9428898ef486184dc93cd06f2b96766a";
    private final static String authorization_code = "";
    //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

    @Override
    public User getCurrentUser(HttpServletRequest request,User user) {
        String id = request.getHeader("id");
        String type = request.getHeader("type");
        String phone = request.getHeader("phone");
        if(!Strings.isNullOrEmpty(id) && id.replace(" ","").length() > 0 && isInteger(id)){
            user.setId(Long.valueOf(id));
        }
        if(!Strings.isNullOrEmpty(type) && type.replace(" ","").length() > 0 && isInteger(type) && type.length() == 1){
            user.setType(Integer.valueOf(type));
        }
        if(!Strings.isNullOrEmpty(phone) && phone.replace(" ","").length() > 0 && isInteger(phone) && phone.length() == 11){
            user.setPhone(phone);
        }
        return user;
    }

    @Override
    public String getWxOpenId(User user) throws Exception{

        //获取用户登陆临时凭证code
        String JSCODE = user.getCode();

        //发起https请求，获取openid和session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+SECRET+"&js_code="+JSCODE+"&grant_type=authorization_code";
        //发送请求
        String data = HttpClientUtils.get(url,"UTF-8",10000,10000);

        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(data);
        //用户的唯一标识（openid）
        String Openid =String.valueOf(json.get("openid"));

        return Openid;
    }

    /**
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
}
